﻿using System;
using System.Web;
using Triad.Controls.Web.Configuration;

namespace Triad.Controls.Web
{
    /// <summary>
    /// Handler for sending files to the client
    /// </summary>
    public class CachingHandler : IHttpHandler
    {
        #region IHttpHandler Members

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        /// <remarks>
        /// Author: tim.fischer,   8/25/2008 - 2:47 PM
        /// Modified By: 
        /// </remarks>
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <remarks>
        /// Author: tim.fischer,   8/25/2008 - 2:48 PM
        /// Modified By: 
        /// </remarks>
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            string file = context.Server.MapPath(context.Request.FilePath.Replace(".ashx", ""));
            string filename = file.Substring(file.LastIndexOf('\\') + 1);
            string extension = file.Substring(file.LastIndexOf('.') + 1);

            var config = (CachingSection)context.GetSection("tfImageCaching/Caching");
            if (config != null)
            {
                context.Response.Cache.SetExpires(DateTime.Now.Add(config.CachingTimeSpan));
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Cache.SetValidUntilExpires(false);

                FileExtension fileExtension = config.FileExtensions[extension];
                if (fileExtension != null)
                {
                    context.Response.ContentType = fileExtension.ContentType;
                }
            }

            context.Response.AddHeader("content-disposition", "inline; filename=" + filename);
            context.Response.WriteFile(file);
        }

        #endregion
    }
}

